<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="form.name" name="姓名" label="姓名" placeholder="姓名" :rules="[{ required: true, message: '请填写姓名' }]" />
      <van-field v-model="form.tel" name="电话" label="电话" placeholder="电话" :rules="[{ required: true, message: '请填写电话' }]" />
      <van-field :modelValue="address" is-link readonly label="地区" placeholder="地区" @click="showPopup = true" :rules="[{ required: true, message: '请选择地区' }]" />
      <van-field v-model="form.detail" name="详细" label="详细" placeholder="详细" :rules="[{ required: true, message: '请填写详细地址' }]" />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 修改 </van-button>
      <van-button round block type="default" @click.prevent="onDelete"> 删除 </van-button>
    </div>
  </van-form>
  <popup v-model:show="showPopup" v-model:provice="provice" v-model:city="city" v-model:region="region"></popup>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import popup from '@/components/popup.vue';
import { type ISelectItem } from '../../types/popup';
import type { IAddress } from '@/types/address';
import { putAddressApi, delAddressApi } from '@/api/address';
import { showConfirmDialog } from 'vant';
import 'vant/lib/dialog/index.css';

const route = useRoute();
const router = useRouter();

const showPopup = ref(false);
const provice = ref<ISelectItem>({ value: 0, name: '' });
const city = ref<ISelectItem>({ value: 0, name: '' });
const region = ref<ISelectItem>({ value: 0, name: '' });
const address = computed(() => {
  return provice.value.name + ' ' + city.value.name + ' ' + region.value.name;
});

const form = ref<IAddress>({
  id: 0,
  name: '姓名',
  tel: '电话',
  address: '',
  code: '',
  detail: '详细地址',
});

onMounted(() => {
  form.value = JSON.parse(route.query.item as string);
  provice.value = { value: form.value.pid as number, name: form.value.pname };
  city.value = { value: form.value.cid as number, name: form.value.cname };
  region.value = { value: form.value.rid as number, name: form.value.rname };
});

const onSubmit = () => {
  putAddressApi({
    ...form.value,
    pname: provice.value.name,
    pid: provice.value.value,
    cname: city.value.name,
    cid: city.value.value,
    code: address.value,
    rname: region.value.name,
    rid: region.value.value,
    address: address.value + form.value.detail,
  }).then(() => {
    router.back();
  });
};
const onDelete = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '确定要删除？',
    width: '80vw',
  })
    .then(() => {
      delAddressApi({ id: Number(form.value.id) }).then(() => {
        router.back();
      });
    })
    .catch((err) => {
      console.log('取消删除', err);
    });
};
</script>

<style lang="scss" scoped></style>
